#include "redis_connection_pool.h"
#include <stdexcept>

namespace redisSpace {
	RedisConnectionPool::RedisConnectionPool(const std::string& host, int port, std::string password, int index, int timeout, int poolSize)
		: host_(host), port_(port), index_(index), password_(password), timeout_({ timeout, 0 }), poolSize_(poolSize) {
		createPool();
	}

	RedisConnectionPool::~RedisConnectionPool() {
		std::lock_guard<std::mutex> lock(mutex_);
		while (!pool_.empty()) {
			pool_.pop();
		}
	}

	void RedisConnectionPool::createPool() {
		if (poolSize_ <= 0) {
			poolSize_ = 8;
		}

		for (int i = 0; i < poolSize_; ++i) {
			auto conn = std::make_shared<RedisConnection>(host_, port_, password_, index_, timeout_);
			if (conn->connect()) {
				pool_.push(conn);
			} else {
				throw std::runtime_error("Failed to create Redis connection");
			}
		}
	}

	std::shared_ptr<RedisConnection> RedisConnectionPool::acquire() {
		std::unique_lock<std::mutex> lock(mutex_);
		while (pool_.empty()) {
			condition_.wait(lock);
		}
		auto conn = pool_.front();
		pool_.pop();
		return conn;
	}

	void RedisConnectionPool::release(redisConnectionPtr conn) {
		std::lock_guard<std::mutex> lock(mutex_);
		pool_.push(conn);
		condition_.notify_one();
	}
}